package com.saascloud.openfeign.core;

import com.saascloud.Constants;
import com.saascloud.core.exception.BizException;
import com.saascloud.core.exception.GlobalErrorCode;
import com.saascloud.core.pojo.R;
import com.saascloud.util.JsonUtils;
import feign.Response;
import feign.codec.ErrorDecoder;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;

import java.io.IOException;
import java.io.Reader;
import java.nio.charset.Charset;

/**
 * @Author: liangxu
 * @Contact: one_dream@aliyun.com
 * @Date: 2022/5/30 14:21
 * @Version: 1.0
 * @Description:
 */
@Slf4j
public class SassFeignErrorDecoder implements ErrorDecoder {

    @Override
    public Exception decode(String methodKey, Response response) {
        log.error("enter feign error decoder for method:{}", methodKey);
        Reader reader = null;
        try {
            if (response.status() == Constants.HttpStatus.BIZ_EXCEPTION_RESP_STATUS) {
                reader = response.body().asReader(Charset.forName("utf-8"));
                String string = IOUtils.toString(reader);
                log.error("resp body:{}", string);
                R R = JsonUtils.string2Obj(string, R.class);
                return new BizException(R.getCode(), R.getMsg());
            }
        } catch (IOException e) {
            log.error("feign error decoder failed,method info:{}", methodKey, e);
        } finally {
            IOUtils.closeQuietly(reader);
        }
        return new BizException(GlobalErrorCode.INTERNAL_SERVER_ERROR);

    }
}
